<template>
  <div class="resource-card" :class="cardClass" @click="handleCardClick">
    <!-- 资源封面 -->
    <div v-if="resource.coverImage" class="resource-cover">
      <img :src="resource.coverImage" :alt="resource.title || '资源封面'" />
      <div v-if="resource.type" class="resource-type-badge">
        {{ getResourceTypeText() }}
      </div>
    </div>
    
    <!-- 资源内容 -->
    <div class="resource-content">
      <!-- 资源分类和标签 -->
      <div class="resource-meta">
        <el-tag v-if="resource.category" type="info" size="small">{{ resource.category.name }}</el-tag>
        <div v-if="resource.tags && resource.tags.length > 0" class="resource-tags">
          <el-tag v-for="(tag, index) in displayedTags" :key="index" type="primary" size="small" :max-width="80">
            {{ typeof tag === 'object' ? tag.name : tag }}
          </el-tag>
          <el-tag v-if="hasMoreTags" type="info" size="small" disabled>
            +{{ resource.tags.length - maxDisplayTags }}
          </el-tag>
        </div>
      </div>
      
      <!-- 资源标题 -->
      <h3 class="resource-title">{{ resource.title || '未命名资源' }}</h3>
      
      <!-- 资源简介 -->
      <p v-if="resource.description" class="resource-description">{{ truncateDescription(resource.description) }}</p>
      
      <!-- 资源统计 -->
      <div class="resource-stats">
        <div class="stat-item">
          <span class="stat-icon"><el-icon><Download /></el-icon></span>
          <span class="stat-value">{{ resource.downloadCount || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon"><el-icon><View /></el-icon></span>
          <span class="stat-value">{{ resource.viewCount || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon"><el-icon><Star /></el-icon></span>
          <span class="stat-value">{{ resource.favoriteCount || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon"><el-icon><Comment /></el-icon></span>
          <span class="stat-value">{{ resource.commentCount || 0 }}</span>
        </div>
      </div>
      
      <!-- 作者信息 -->
      <div v-if="showAuthor && resource.author" class="resource-author">
        <div class="author-avatar">
          <img :src="resource.author.avatar || defaultAvatar" :alt="resource.author.username || '作者头像'" />
        </div>
        <div class="author-info">
          <span class="author-name">{{ resource.author.username || '匿名用户' }}</span>
          <span class="publish-time">{{ resource.createdAt ? formatDate(resource.createdAt) : '' }}</span>
        </div>
      </div>
      
      <!-- 自定义内容 -->
      <div v-if="$slots.content" class="resource-custom-content">
        <slot name="content" :resource="resource" />
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div v-if="showActions" class="resource-actions">
      <button
        v-if="canDownload"
        class="action-btn action-download"
        @click.stop="handleDownload"
        :disabled="isDownloading"
      >
        <el-icon><Download /></el-icon>
        <span>下载</span>
      </button>
      <button
        v-if="canView"
        class="action-btn action-view"
        @click.stop="handleView"
      >
        <el-icon><View /></el-icon>
        <span>查看</span>
      </button>
      <button
        v-if="canFavorite && !isFavorite"
        class="action-btn action-favorite"
        @click.stop="handleFavorite"
      >
        <el-icon><Star /></el-icon>
      </button>
      <button
        v-if="canFavorite && isFavorite"
        class="action-btn action-favorite active"
        @click.stop="handleUnfavorite"
      >
        <el-icon><StarFilled /></el-icon>
      </button>
      <button
        v-if="canComment"
        class="action-btn action-comment"
        @click.stop="handleComment"
      >
        <el-icon><Comment /></el-icon>
      </button>
      <button
        v-if="canEdit"
        class="action-btn action-edit"
        @click.stop="handleEdit"
      >
        <el-icon><Edit /></el-icon>
      </button>
      <button
        v-if="canDelete"
        class="action-btn action-delete"
        @click.stop="handleDelete"
      >
        <el-icon><Delete /></el-icon>
      </button>
    </div>
    
    <!-- 资源状态标签 -->
    <div v-if="resource.status !== 'published'" class="resource-status-badge" :class="`status-${resource.status}`">
      {{ getStatusText() }}
    </div>
    
    <!-- 热门/推荐标签 -->
    <div v-if="resource.isHot" class="resource-featured-badge hot">
      热门
    </div>
    <div v-if="resource.isRecommended" class="resource-featured-badge recommended">
      推荐
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, withDefaults, defineProps, defineEmits } from 'vue'
import { useRouter } from 'vue-router'
import { ElTag, ElIcon } from 'element-plus'
import {
  Download,
  View,
  Star,
  StarFilled,
  Comment,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import type { LearningResource } from '../types/resource'
import type { User } from '../types/user'
import type { Tag } from '../types/tag'
import { formatDate, truncateString as truncateText } from '../utils/common'

// 默认头像
const defaultAvatar = '/default-avatar.png'

// 创建自定义Resource类型以覆盖category属性
interface CustomResource extends Omit<LearningResource, 'category' | 'tags'> {
  category?: { id?: number; name?: string }
  tags?: (Partial<Tag> | string)[]
  author?: Partial<User>
  price?: number
  isFree?: boolean
}

// Props
interface Props {
  resource: Partial<CustomResource & {
    viewCount?: number
    downloadCount?: number
    favoriteCount?: number
    commentCount?: number
  }>
  currentUserId?: string | number
  isFavorite?: boolean
  showAuthor?: boolean
  showActions?: boolean
  canView?: boolean
  canDownload?: boolean
  canFavorite?: boolean
  canComment?: boolean
  canEdit?: boolean
  canDelete?: boolean
  size?: 'small' | 'medium' | 'large'
  maxDisplayTags?: number
}

const props = withDefaults(defineProps<Props>(), {
  resource: () => ({}),
  isFavorite: false,
  showAuthor: true,
  showActions: true,
  canView: true,
  canDownload: true,
  canFavorite: true,
  canComment: true,
  canEdit: false,
  canDelete: false,
  size: 'medium',
  maxDisplayTags: 3
})

// Router
const router = useRouter()

// Emits
const emit = defineEmits<{
  'view': [resource: Partial<CustomResource>]
  'download': [resource: Partial<CustomResource>]
  'favorite': [resource: Partial<CustomResource>]
  'unfavorite': [resource: Partial<CustomResource>]
  'comment': [resource: Partial<CustomResource>]
  'edit': [resource: Partial<CustomResource>]
  'delete': [resource: Partial<CustomResource>]
}>()

// Refs
const isDownloading = ref(false)
const internalIsFavorite = ref(props.isFavorite)

// 计算属性
const cardClass = computed(() => {
  return [
    `resource-card-${props.size}`,
    {
      'resource-card-hot': props.resource.isHot,
      'resource-card-recommended': props.resource.isRecommended,
      'resource-card-free': props.resource.isFree,
      'resource-card-paid': !props.resource.isFree && props.resource?.price && props.resource.price! > 0
    }
  ]
})

// 显示的标签数量
const displayedTags = computed(() => {
  return props.resource.tags?.slice(0, props.maxDisplayTags) || []
})

// 是否有更多标签
const hasMoreTags = computed(() => {
  return props.resource.tags && props.resource.tags.length > props.maxDisplayTags
})

// 获取资源类型文本
const getResourceTypeText = () => {
  const typeMap: Record<string, string> = {
    'document': '文档',
    'video': '视频',
    'audio': '音频',
    'image': '图片',
    'link': '链接',
    'archive': '压缩包'
  }
  return typeMap[props.resource.type as string] || '资源'
}

// 获取资源状态文本
const getStatusText = () => {
  const statusMap: Record<string, string> = {
    'draft': '草稿',
    'pending': '审核中',
    'published': '已发布',
    'rejected': '已拒绝',
    'archived': '已归档'
  }
  return statusMap[props.resource.status as string] || '未知状态'
}

// 截断描述文本
const truncateDescription = (description: string) => {
  const maxLength = props.size === 'small' ? 60 : props.size === 'medium' ? 100 : 150
  return truncateText(description, maxLength)
}

// 事件处理
const handleCardClick = () => {
  if (props.resource.id) {
    // 跳转到资源详情页
    router.push(`/resource/${props.resource.id}`)
  }
}

const handleView = () => {
  if (props.resource.id) {
    // 跳转到资源详情页
    router.push(`/resource/${props.resource.id}`)
  }
  emit('view', props.resource)
}

const handleDownload = async () => {
  if (isDownloading.value) return
  
  isDownloading.value = true
  try {
    emit('download', props.resource)
    // 模拟下载完成
    setTimeout(() => {
      isDownloading.value = false
    }, 1500)
  } catch (error) {
    isDownloading.value = false
  }
}

const handleFavorite = () => {
  emit('favorite', props.resource)
  internalIsFavorite.value = true
}

const handleUnfavorite = () => {
  emit('unfavorite', props.resource)
  internalIsFavorite.value = false
}

const handleComment = () => {
  emit('comment', props.resource)
}

const handleEdit = () => {
  emit('edit', props.resource)
}

const handleDelete = () => {
  emit('delete', props.resource)
}

// 暴露方法
defineExpose({
  view: handleView,
  download: handleDownload,
  toggleFavorite: () => {
    if (internalIsFavorite.value) {
      handleUnfavorite()
    } else {
      handleFavorite()
    }
  },
  setIsDownloading: (status: boolean) => {
    isDownloading.value = status
  }
})
</script>

<style scoped>
.resource-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  flex-direction: column;
}

.resource-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 尺寸样式 */
.resource-card-small {
  flex-direction: row;
}

.resource-card-small .resource-cover {
  width: 100px;
  height: 100px;
  flex-shrink: 0;
}

.resource-card-small .resource-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.resource-card-medium {
  max-width: 380px;
  margin: 0 auto;
}

/* 资源封面 */
.resource-cover {
  width: 100%;
  height: 180px;
  overflow: hidden;
  position: relative;
}

.resource-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.resource-card:hover .resource-cover img {
  transform: scale(1.05);
}

.resource-type-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  padding: 4px 8px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* 资源内容 */
.resource-content {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 资源元数据 */
.resource-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.resource-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 资源标题 */
.resource-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 资源描述 */
.resource-description {
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
  margin: 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 资源统计 */
.resource-stats {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-top: 1px solid #f0f2f5;
  margin: 8px 0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.stat-icon {
  font-size: 14px;
}

.stat-value {
  font-weight: 500;
  color: #606266;
}

/* 作者信息 */
.resource-author {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f2f5;
  margin-top: auto;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
}

.author-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.author-info {
  flex: 1;
}

.author-name {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.publish-time {
  display: block;
  font-size: 12px;
  color: #909399;
}

/* 操作按钮 */
.resource-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-top: 1px solid #f0f2f5;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  background-color: transparent;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  gap: 4px;
}

.action-btn:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.action-download {
  background-color: #409eff;
  color: white;
  margin-right: auto;
}

.action-download:hover:not(:disabled) {
  background-color: #66b1ff;
  color: white;
}

.action-download:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.action-view {
  background-color: #67c23a;
  color: white;
  margin-right: auto;
}

.action-view:hover {
  background-color: #85ce61;
  color: white;
}

.action-favorite.active {
  color: #f56c6c;
}

.action-edit:hover {
  color: #e6a23c;
}

.action-delete:hover {
  color: #f56c6c;
}

/* 资源状态标签 */
.resource-status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  z-index: 10;
}

.status-draft {
  background-color: #909399;
}

.status-pending {
  background-color: #e6a23c;
}

.status-published {
  background-color: #67c23a;
}

.status-rejected {
  background-color: #f56c6c;
}

.status-archived {
  background-color: #606266;
}

/* 热门/推荐标签 */
.resource-featured-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  z-index: 10;
}

.resource-featured-badge.hot {
  background-color: #f56c6c;
}

.resource-featured-badge.recommended {
  background-color: #409eff;
}

/* 付费/免费标签 */
.resource-card-paid::before {
  content: '💰 付费';
  position: absolute;
  top: 8px;
  left: 8px;
  padding: 4px 8px;
  background-color: rgba(245, 108, 108, 0.9);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  z-index: 10;
}

.resource-card-free::before {
  content: '🆓 免费';
  position: absolute;
  top: 8px;
  left: 8px;
  padding: 4px 8px;
  background-color: rgba(103, 194, 58, 0.9);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  z-index: 10;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .resource-card-small {
    flex-direction: column;
  }
  
  .resource-card-small .resource-cover {
    width: 100%;
    height: 120px;
  }
  
  .resource-title {
    font-size: 16px;
  }
  
  .resource-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .action-btn {
    flex: 1;
    min-width: 40%;
  }
}

@media (max-width: 480px) {
  .resource-cover {
    height: 120px;
  }
  
  .resource-content {
    padding: 12px;
  }
  
  .resource-actions {
    padding: 12px;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>